package com.gjp.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/shiro")
public class ShiroLoginController
{

	@RequestMapping("/login")
	public ModelAndView login(
			@RequestParam("username") String username,
			@RequestParam("password") String password)
	{
		//定义返回对象
		ModelAndView modelAndView = new ModelAndView();
		//创建Subject(这个就代表当前用户)
		Subject currentUser = SecurityUtils.getSubject();
		// 如果用户没登录，则走调用登录方法，否则直接跳转到成功页面
		if (!currentUser.isAuthenticated())
		{
			// 把用户名和密码封装为UsernamePasswordToken对象
			UsernamePasswordToken token = new UsernamePasswordToken(username,password);
			
			
			try
			{
				// 调用login方法，登录，
				//此处方法会进入到ShiroRealm类中执行doGetAuthenticationInfo()方法
				currentUser.login(token);
			} catch (AuthenticationException ae)
			{
				//如果登录失败，则统一提示账号密码错误，其实还有很多对应异常
				//例如，账号不存在，密码错误，用户被锁定等等
				//将错误信息存入到scope中，并跳转到当前页面，显示错误信息
				modelAndView.addObject("errorMsg", "账号或密码错误！");
				modelAndView.setViewName("login");
				return modelAndView;
			}
		}
		// 跳转到相应的处理页面
		// redirect:/list.jsp
		modelAndView.setViewName("redirect:/list.jsp");
		return modelAndView;
	}
	
	@RequestMapping("/loginrolean")
//	@RequiresRoles("admin")
	public ModelAndView needAdminRoleAn(){
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("redirect:/a.jsp");
		return modelAndView;
		
	}
	
	@RequestMapping("/loginrolecode")
	public ModelAndView needAdminRoleCode(){
		
		Subject subject = SecurityUtils.getSubject();
		ModelAndView modelAndView = new ModelAndView();
		if(subject.hasRole("admin")){
			
			modelAndView.setViewName("redirect:/a.jsp");
		}else{
			modelAndView.setViewName("redirect:/b.jsp");
		}
		
		return modelAndView;
		
		
		
	}
	
	
	@RequestMapping("/loginresource")
	@RequiresPermissions("test3")
	public ModelAndView needResource(){
		
		Subject subject = SecurityUtils.getSubject();
		ModelAndView modelAndView = new ModelAndView();
		if(subject.hasRole("admin")){
			
			modelAndView.setViewName("redirect:/a.jsp");
		}else{
			modelAndView.setViewName("redirect:/b.jsp");
		}
		
		return modelAndView;
		
		
		
	}
	

}
